package com.XDApp.xdbase;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.XDApp.xdbase.bean.UpdateInfo;

public class BaseApplication extends Application {
	
	private Bitmap mDefaultAvatar;
	
	/**
	 * 更新信息
	 */
	public UpdateInfo updateInfo;
	
	private static final String AVATAR_DIR = "avatar/";
	public Map<String, SoftReference<Bitmap>> mAvatarCache ;
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		mAvatarCache = new HashMap<String, SoftReference<Bitmap>>();
		mDefaultAvatar = BitmapFactory.decodeResource(getResources(),
				R.drawable.default_avatar);
		
		
		JPushInterface.setDebugMode(true);
		JPushInterface.init(this);

	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		Log.e("BaseApplication", "onLowMemory");
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		Log.e("BaseApplication", "onTerminate");
	}
	
	public Bitmap getAvatar(String imageName) {
		if (mAvatarCache.containsKey(imageName)) {
			Reference<Bitmap> reference = mAvatarCache.get(imageName);
			if (reference.get() == null || reference.get().isRecycled()) {
				mAvatarCache.remove(imageName);
			} else {
				return reference.get();
			}
		}
		InputStream is = null;
		Bitmap bitmap = null;
		try {
			/*************************获取流**********************/
			is = getAssets().open(AVATAR_DIR + imageName);
			/*******************************************************/
			bitmap = BitmapFactory.decodeStream(is);
			if (bitmap == null) {
				throw new FileNotFoundException(imageName + "is not find");
			}
			mAvatarCache.put(imageName, new SoftReference<Bitmap>(bitmap));
			return bitmap;
		} catch (Exception e) {
			return mDefaultAvatar;
		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (IOException e) {

			}
		}
	}
}
